package com.funny;

import java.io.IOException;
import java.util.Properties;

import org.slim3.datastore.Datastore;

import com.funny.model.AppSetting;
import com.google.appengine.api.NamespaceManager;
import com.google.appengine.api.datastore.Key;

/**
 * Configuration for application.
 * @author nvhien
 */
public class Configuration {

	private static Configuration instance = new Configuration();

	private final String systemEmail;

	private final String systemName;


	/**
	 * reload settings.
	 */
	public static void reload() {
		instance = new Configuration();
	}

	private Configuration() {
		String namespace = NamespaceManager.get();
		NamespaceManager.set(null);
		try {
			Key key = Datastore.createKey(AppSetting.class, "appsetting");
			AppSetting setting = Datastore.getOrNull(AppSetting.class, key);
			if (setting != null) {
				systemEmail = setting.getSystemEmail();
				systemName = setting.getSystemName();
			} else {
				Properties properties = new Properties();
				try {
					properties.load(Configuration.class
						.getResourceAsStream("/configuration.properties"));
				} catch (IOException e) {
					e.printStackTrace();
				}
				systemEmail = properties.getProperty("systemEmail");
				systemName = properties.getProperty("systemName");
				AppSetting appSetting = new AppSetting();
				appSetting.setKey(key);
				appSetting.setSystemEmail(systemEmail);
				appSetting.setSystemName(systemName);
				try {
					Datastore.put(appSetting);
				} catch (Throwable th) {
					//
				}
			}
		} finally {
			NamespaceManager.set(namespace);
		}
	}

	/**
	 * @return instance
	 */
	public static Configuration get() {
		return instance;
	}

	/**
	 * @return the systemEmail
	 * @category accessor
	 */
	public String getSystemEmail() {
		return systemEmail;
	}

	/**
	 * @return the systemName
	 * @category accessor
	 */
	public String getSystemName() {
		return systemName;
	}
}
